package handler

import (
	"context"
	"gitee.com/duan_shengjie/user/domain/model"
	"gitee.com/duan_shengjie/user/domain/service"

	user "gitee.com/duan_shengjie/user/proto/user"
)

type User struct {
	UserDataService service.IUserDataService
}

func (u *User) RegisterUser(ctx context.Context, req *user.RegisterUserReq, res *user.RegisterUserRes) error {
	userRegister := &model.User{
		UserName:     req.UserName,
		FirstName:    req.GetFirstName(),
		HashPassword: req.Pwd,
	}
	_, err := u.UserDataService.AddUser(userRegister)
	if err != nil {
		return err
	}
	res.Message = "用户注册成功！"
	return err
}
func (u *User) UserLogin(ctx context.Context, req *user.UserLoginReq, res *user.UserLoginRes) (err error) {
	res.Message = "登录失败"
	ok, err := u.UserDataService.CheckPwd(req.UserName, req.Pwd)
	if err != nil {
		return err
	}
	if ok {
		res.Message = "登录成功"
	}
	return
}
func (u *User) GetUserInfo(ctx context.Context, req *user.GetUserInfoReq, res *user.GetUserInfoRes) (err error) {
	userModel, err := u.UserDataService.FindUserByName(req.UserName)
	if err != nil {
		return err
	}
	res = UserForResponse(userModel)
	return
}

func UserForResponse(userModel *model.User) *user.GetUserInfoRes {
	res := new(user.GetUserInfoRes)
	res.UserId = userModel.ID
	res.UserName = userModel.UserName
	res.FirstName = userModel.FirstName
	return res
}
